package com.whfp.coky.db;

import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.database.transaction.ProcessModelTransaction;
import com.whfp.afs330h_sdk.bean.BLE_TestingResultBean;
import com.whfp.afs330h_sdk.utils.RxConstants;
import com.whfp.afs330h_sdk.utils.RxUtils;
import com.whfp.coky.db.dao.JsonBQDao;
import com.whfp.coky.db.dao.JsonBQDao_Table;
import com.whfp.coky.db.dao.ProjectSettingDao;
import com.whfp.coky.db.dao.ProjectSettingDao_Table;
import com.whfp.coky.db.dao.TestingRecordingDao;
import com.whfp.coky.db.dao.TestingRecordingDao_Table;
import com.whfp.coky.db.dbflow.AppDatabase;
import com.whfp.coky.other.Constants;
import com.whfp.coky.utils.LogUtil;
import com.whfp.coky.utils.RxTimeTool;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * CRUD操作工具类
 */
public class DbFlowTools {

    public static List<ProjectSettingDao> querySettingsByPage(int page){
        return SQLite.
                select().
                from(ProjectSettingDao.class).
                offset((page-1) * Constants.Companion.getPAGE_SIZE()).
                limit(Constants.Companion.getPAGE_SIZE()).
                queryList();
    }


    /**
     * 根据毒品名称查询对应的阈值设置信息
     *
     * @param drugName 毒品名称
     * @return 查询结果
     */
    public static ProjectSettingDao inquiryToName(String drugName) {
        ProjectSettingDao projectSettingDao = SQLite.select()
                .from(ProjectSettingDao.class)
                .where(ProjectSettingDao_Table.projectName.eq(drugName))
                .querySingle();
        return projectSettingDao;
    }

    /**
     * 根据毒品名称查询对应的阈值设置信息
     *
     * @param id 项目设置ID
     * @return 查询结果
     */
    public static ProjectSettingDao inquiryById(int id) {
        ProjectSettingDao projectSettingDao = SQLite.select()
                .from(ProjectSettingDao.class)
                .where(ProjectSettingDao_Table.id.is(id))
                .querySingle();
        return projectSettingDao;
    }

    /**
     * 根据ID修改对应的设置数据
     *
     * @param id     设置记录ID
     * @param newDao 要修改的数据
     * @return 修改结果
     */
    public static boolean updateProjectSetingById(int id, ProjectSettingDao newDao) {
        ProjectSettingDao projectSettingDao = SQLite.select()
                .from(ProjectSettingDao.class)
                .where(ProjectSettingDao_Table.id.is(id))
                .querySingle();
        if (projectSettingDao != null) {
            projectSettingDao.setProjectName(newDao.getProjectName());
            projectSettingDao.setDensityUnit(newDao.getDensityUnit());
            projectSettingDao.setThresholdInfo(newDao.getThresholdInfo());
            boolean is = projectSettingDao.update();
            if (is) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


    /**
     * 倒序查询最后一条检测记录
     *
     * @return
     */
    public static TestingRecordingDao inquiryLatestRecording() {
        TestingRecordingDao dao = SQLite.select()
                .from(TestingRecordingDao.class)
                .orderBy(TestingRecordingDao_Table.id, false)
                .querySingle();
        return dao;
    }

    /**
     * 倒序查询最后一条未上传的检测记录
     *
     * @return
     */
    public static TestingRecordingDao inquiryLastNoUploadTestRecording() {
        TestingRecordingDao dao = SQLite.select()
                .from(TestingRecordingDao.class)
                .where(TestingRecordingDao_Table.isUpload.eq(false))
                .orderBy(TestingRecordingDao_Table.id, false)
                .querySingle();
        return dao;
    }

    /**
     * 根据ID修改对应的检测记录上传状态
     *
     * @param id
     * @return
     */
    public static void updateTestRecordingUpload(int id) {
        SQLite.update(TestingRecordingDao.class)
                .set(TestingRecordingDao_Table.isUpload.eq(true))
                .where(TestingRecordingDao_Table.id.is(id))
                .execute();
    }

    /**
     * 批量插入项目设置
     *
     * @param daoList
     */
    public static void insertProjectSettingList(List<ProjectSettingDao> daoList) {
        FlowManager.getDatabase(AppDatabase.class)
                .executeTransaction(new ProcessModelTransaction.Builder<ProjectSettingDao>(
                        BaseModel::insert
                ).addAll(daoList).build());
    }

    /**
     * 根据标曲编号查询对应的JSON标曲
     *
     * @param bqNumber 标曲编号
     * @return
     */
    public static JsonBQDao inquiryToBqName(String bqNumber) {
        return SQLite.select()
                .from(JsonBQDao.class)
                .where(JsonBQDao_Table.bqName.eq(bqNumber))
                .querySingle();
    }

    /**
     * 插入一条json标曲到库中
     *
     * @param jsonBQDao
     */
    public static void insertBqJson(JsonBQDao jsonBQDao) {
        FlowManager.getDatabase(AppDatabase.class)
                .executeTransaction(new ProcessModelTransaction.Builder<JsonBQDao>(
                        BaseModel::insert
                ).add(jsonBQDao).build());
    }



    /**
     * 往检测记录表里插入本次测试数据
     *
     * @param testingRecordingDao
     * @return
     */
    public static  TestingRecordingDao insertTestingData(TestingRecordingDao testingRecordingDao) throws UnsupportedEncodingException {
        //将检测结果转为json字符串
//        String json = GsonUtils.toJson(testVoBeans);
//        LogUtil.e("这是个啥啊？" + json);
        String currentTime = RxTimeTool.getCurrentDateTime("yyyyMMdd");
        //查询当天已测试了几次来获得流水号后四位
        int t = SQLite.select().from(TestingRecordingDao.class).
                where(TestingRecordingDao_Table.testingTime.like(TextUtils.concat(currentTime, "%").toString()))
                .queryList().size() + 1;
//        LogUtil.e("查到当天的条数：" + t);
//        String ls = NumberUtils.format(t, 4, 0, false);
//        LogUtil.e("格式化后的值：" + ls);
//        String gbkProject = new String(EncodeUtils.base64Decode(bean.getTitle()), "GB2312");
//        LogUtil.e("检测项目：" + gbkProject);


        boolean r = testingRecordingDao.save();

//        LogUtil.e("插入结果：" + r + "id是什么：" + testingRecordingDao.getId() + "附件本地路径：" + testingRecordingDao.getFilesPath());

//        if (RxStringTool.isEmpty(getActivityIntentType())) {//为空则是属于正常点击进入
//            //显示打印结果按钮
//            btnPrint.setVisibility(View.VISIBLE);
//            LogUtil.e("1111111111111111111111mmmmmmmmmmmmmmmmmmmmmmmmmm");
//        } else {//不为空则是属于一个子任务
//            switch (getActivityIntentType()) {
//                case com.whfp.zxwl.utils.RxConstants.INTENT_TYPE_TASK_YGJC://荧光检测（破冰2号检测）
//                    btn_submit.setVisibility(View.VISIBLE);
//                    break;
//            }
//            LogUtil.e("1111111111111111111111");
//        }


        clearTestingData();

        return r?testingRecordingDao:null;
    }

    //查询倒序前10000条记录之外的所有记录并删除
    private static  void clearTestingData(){
        List<TestingRecordingDao> testingDatas = SQLite.select().from(TestingRecordingDao.class).orderBy(TestingRecordingDao_Table.testingTime, false)
                .limit(100)//选取100个数据
                .offset(10000)//跳过10000个数据
                .queryList();
        if (testingDatas != null && testingDatas.size() > 0) {
            for (TestingRecordingDao daoBean : testingDatas) {
                daoBean.delete();
            }
        }
    }



}
